﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Linq;
using Ample.Model;

namespace Ample.DAL
{
    public static class OrderLinqQueries
    {
        public static readonly Func<AmpleDataContext, string, IEnumerable<Order>> CompiledQuery_GetOrderWithLatestStatusByUsername =
            CompiledQuery.Compile<AmpleDataContext, string, IEnumerable<Order>>((adc, username) =>
                    
                    from o in adc.Orders.Where(o => o.User.UserName == username).ToList<Order>()
                    select o
            );

        public static readonly Func<AmpleDataContext, string, DateTime, DateTime , IEnumerable<Order>> CompiledQuery_GetOrderWithLatestStatus =
            CompiledQuery.Compile<AmpleDataContext, string, DateTime , DateTime , IEnumerable<Order>>((adc, status, fromDate, toDate) =>

                    from o in adc.Orders.Where(o => (o.AddedDate >= fromDate && o.AddedDate <= toDate && 
                        (from os in o.OrderStatuses
                                  where os.AddedDate == o.OrderStatuses.Max(i => i.AddedDate)
                                  select os.Status).SingleOrDefault() == status )).ToList<Order>()
                    select o
            );

        public static readonly Func<AmpleDataContext, int, IEnumerable<Order>> CompiledQuery_GetOrderByOrderId =
           CompiledQuery.Compile<AmpleDataContext, int, IEnumerable<Order>>((adc, Id) =>

                   from o in adc.Orders.Where(o => o.OrderId == Id).ToList<Order>()
                   select o
           );

        public static readonly Func<AmpleDataContext, string, IEnumerable<Order>> CompiledQuery_GetOrderByOrderNo =
           CompiledQuery.Compile<AmpleDataContext, string, IEnumerable<Order>>((adc, No) =>

                   from o in adc.Orders.Where(o => o.OrderNo == No).ToList<Order>()
                   select o
           );

        public static readonly DataLoadOptions OrderStatus_Options_With_Order =
            (new Func<DataLoadOptions>(() =>
            {
                DataLoadOptions option = new DataLoadOptions();

                option.LoadWith<Order>(o => o.User);
                option.LoadWith<Order>(o => o.OrderStatuses);
                option.LoadWith<Order>(o => o.OrderItems);
                
                return option;
            }))();

    }
}
